<?php
/**
 * SweetPlurk
 *
 * @package    SweetPlurk
 * @copyright  Copyright (c) 2008-2012 Wabow Information Inc. (http://www.wabow.com)
 * @license    New BSD License
 * @version    $Id$
 */

/**
 * Connector By Curl
 *
 * @package    SweetPlurk
 * @copyright  Copyright (c) 2008-2012 Wabow Information Inc. (http://www.wabow.com)
 * @license    New BSD License
 */
class SweetPlurk_Connector_Curl extends SweetPlurk_Connector
{
    /**
     * 初始化 HTTP 連線
     *
     */
    protected function _init()
    {
        $curlOptions = array(
            CURLOPT_RETURNTRANSFER          => true,
            CURLOPT_HEADER                  => false,
            CURLOPT_FOLLOWLOCATION          => true,
            CURLOPT_COOKIESESSION           => true,
            CURLOPT_ENCODING                => "",
            CURLOPT_USERAGENT               => "PlurkAPI",
            CURLOPT_AUTOREFERER             => true,
            CURLOPT_CONNECTTIMEOUT          => 120,
            CURLOPT_TIMEOUT                 => 120,
            CURLOPT_MAXREDIRS               => 10,
            CURLOPT_POST                    => true,
            CURLOPT_SSL_VERIFYHOST          => false,
            CURLOPT_SSL_VERIFYPEER          => false,
            CURLOPT_VERBOSE                 => false,
        );
        $this->_handler = curl_init();
        curl_setopt_array($this->_handler, $curlOptions);
    }

    /**
     * 設定 Cookie
     *
     */
    protected function _setCookie()
    {
        curl_setopt($this->_handler, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($this->_handler, CURLOPT_COOKIEJAR, $this->_options['cookiePath']);
        curl_setopt($this->_handler, CURLOPT_COOKIEFILE, $this->_options['cookiePath']);
    }

    /**
     * 關閉資源
     *
     */
    protected function _close()
    {
        curl_close($this->_handler);
    }

    /**
     * 傳送 POST 資訊
     *
     * @param string $url
     * @param array $data
     * @return string
     */
    protected function _post($url, $data)
    {
        curl_setopt($this->_handler, CURLOPT_URL, $url);
        curl_setopt($this->_handler, CURLOPT_POST, true);
        curl_setopt($this->_handler, CURLOPT_POSTFIELDS, http_build_query($data));
        $result = curl_exec($this->_handler);

        if (CURLE_OK !== curl_errno($this->_handler)) {
            $info = curl_getinfo($this->_handler);
            throw new Exception(print_r($info, true));
        } else {
            return $result;
        }
    }
}